//
//  LoginVM.m
//  WanCaiC8
//
//  Created by tangang on 2018/3/29.
//  Copyright © 2018年 tangang. All rights reserved.
//

#import "LoginVM.h"

@implementation LoginVM{
    dispatch_source_t _timer;
}

- (void)validateWithMobile:(NSString *)phone andSuccess:(SuccessBlock)success andFail:(FailBlock)fail{
    [SVProgressHUD show];
    [self GET_Field_Url:@"api/Auth/ValidateMobile" Params:@{@"phone":phone} successBlock:^(id returnValue) {
        if ([[returnValue objectForKey:@"Code"] intValue]==APIResponseStutusSuccess) {
            success(returnValue);
        }else{
//            [SVProgressHUD showErrorWithStatus:[returnValue objectForKey:@"Desc"]];
            fail([returnValue objectForKey:@"Code"],nil);
        }
    } failBlock:^(NSString *errorMessage, NSError *error) {
        [SVProgressHUD showErrorWithStatus:errorMessage];
        fail(errorMessage,nil);
    }];
}

- (void)registerWithUserInfo:(NSDictionary *)dict andSuccess:(SuccessBlock)success andFail:(FailBlock)fail{
    [self POST_Field_Url:@"api/Auth/Register" Params:dict successBlock:^(id returnValue) {
        if ([[returnValue objectForKey:@"Code"] intValue]==APIResponseStutusSuccess) {
            [UserModel saveModel:[returnValue objectForKey:@"Data"]];
            [UserModel setPwd:[dict objectForKey:@"Password"]];
            success(returnValue);
        }else{
            [SVProgressHUD showErrorWithStatus:[returnValue objectForKey:@"Desc"]];
            fail(nil,nil);
        }
    } failBlock:^(NSString *errorMessage, NSError *error) {
        [SVProgressHUD showErrorWithStatus:errorMessage];
        fail(nil,nil);
    }];
}

- (void)loginWithAccount:(NSString *)account andPassword:(NSString *)password andSuccess:(SuccessBlock)success andFail:(FailBlock)fail{
    [self POST_Field_Url:@"api/Auth/Login" Params:@{@"Account":account,@"Password":password} successBlock:^(id returnValue) {
        if ([[returnValue objectForKey:@"Code"] intValue]==APIResponseStutusSuccess) {
            [UserModel saveModel:[returnValue objectForKey:@"Data"]];
            [UserModel setPwd:password];
            success(returnValue);
        }else{
            [SVProgressHUD showErrorWithStatus:[returnValue objectForKey:@"Desc"]];
            fail(nil,nil);
        }
    } failBlock:^(NSString *errorMessage, NSError *error) {
        [SVProgressHUD showErrorWithStatus:errorMessage];
        fail(nil,nil);
    }];
}

- (void)forgetPassword:(NSDictionary *)userInfo andSuccess:(SuccessBlock)success andFail:(FailBlock)fail{
    [self POST_Field_Url:@"api/Auth/ForgotPassword" Params:userInfo successBlock:^(id returnValue) {
        if ([[returnValue objectForKey:@"Code"] intValue]==APIResponseStutusSuccess) {
            success(returnValue);
            [SVProgressHUD showSuccessWithStatus:@"修改密码成功"];
        }else{
            [SVProgressHUD showErrorWithStatus:[returnValue objectForKey:@"Desc"]];
            fail(nil,nil);
        }
    } failBlock:^(NSString *errorMessage, NSError *error) {
        [SVProgressHUD showErrorWithStatus:errorMessage];
        fail(nil,nil);
    }];
}

- (void)outLogin{
    [self POST_Field_Url:@"api/Auth/Logout" Params:nil successBlock:^(id returnValue) {
    } failBlock:^(NSString *errorMessage, NSError *error) {
    }];
}

- (void)getVerificationCode:(NSString *)phone andSuccess:(SuccessBlock)endBlock andContinue:(SuccessBlock)continueBlock{
    if (self.time==0) {
        WS(weakSelf);
        [self GET_Field_Url:@"api/Common/GetSmsCode" Params:@{@"phone":phone} successBlock:^(id returnValue) {
            weakSelf.time=60;
            [weakSelf getVerificationCode:phone andSuccess:endBlock andContinue:continueBlock];
        } failBlock:^(NSString *errorMessage, NSError *error) {
            [SVProgressHUD showErrorWithStatus:errorMessage];
        }];
    }else{
        [self cancleTimer];
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(_timer,DISPATCH_TIME_NOW,1.0*NSEC_PER_SEC, 0);
        dispatch_source_set_event_handler(_timer, ^{
            if(self.time<=0){
                dispatch_source_cancel(_timer);
                _timer=nil;
                dispatch_async(dispatch_get_main_queue(), ^{
                    endBlock(nil);
                });
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.time--;
                    continueBlock([NSString stringWithFormat:@"%ds以后重新发送",self.time]);
                });
            }
        });
        dispatch_resume(_timer);
    }
    
}

- (void)cancleTimer{
    if (_timer) {
        dispatch_source_cancel(_timer);
    }
}

static LoginVM *n_manager=nil;
+ (LoginVM *)manage{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        n_manager=[[LoginVM alloc]init];
    });
    return n_manager;
}
@end
